﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Collections;
using System.IO;
namespace SmartCollection
{
    class SmartCollectionBase
    {
        TheGioiPhaiDep_DataEntities db = new TheGioiPhaiDep_DataEntities();
        public Product SaveProduct(ProductBase pro)
        {

            Product p = new Product();
            if (pro.Price.IsNumber())
            {
                p.Name = pro.Name;
                p.Price = decimal.Parse(pro.Price);
                p.Sku = pro.Code;
                p.FullDescription = pro.FullDescription;
                p.ShortDescription = pro.ShortDescription;

                p.Published = true;
                p.ProductTypeId = 5;
                p.ParentGroupedProductId = 0;
                p.VisibleIndividually = true;
                p.ProductTemplateId = 1;
                p.ShowOnHomePage = true;
                p.AllowCustomerReviews = true;
                p.ApprovedRatingSum = 5;
                p.NotApprovedRatingSum = 0;
                p.ApprovedTotalReviews = 1;
                p.NotApprovedTotalReviews = 0;
                p.SubjectToAcl = false;
                p.LimitedToStores = false;
                p.IsGiftCard = false;
                p.GiftCardTypeId = 0;
                p.RequireOtherProducts = false;
                p.AutomaticallyAddRequiredProducts = false;
                p.IsDownload = false;
                p.DownloadId = 0;
                p.UnlimitedDownloads = false;
                p.MaxNumberOfDownloads = 0;
                p.DownloadActivationTypeId = 0;
                p.HasSampleDownload = false;
                p.SampleDownloadId = 0;
                p.HasUserAgreement = false;
                p.IsRecurring = false;
                p.RecurringCycleLength = 0;
                p.RecurringCyclePeriodId = 0;
                p.RecurringTotalCycles = 0;
                p.IsShipEnabled = false;
                p.IsFreeShipping = false;
                p.AdditionalShippingCharge = 0;
                p.DeliveryDateId = 0;
                p.WarehouseId = 0;
                p.IsTaxExempt = false;
                p.TaxCategoryId = 0;// loai

                p.ManageInventoryMethodId = 0; // show url to run 
                p.StockQuantity = 10000;
                p.DisplayStockAvailability = true;
                p.DisplayStockQuantity = false;
                p.MinStockQuantity = 0;
                p.LowStockActivityId = 0;
                p.NotifyAdminForQuantityBelow = 1;

                p.BackorderModeId = 0;
                p.AllowBackInStockSubscriptions = false;
                p.OrderMinimumQuantity = 1;
                p.OrderMaximumQuantity = 100;
                p.DisableBuyButton = false;
                p.DisableWishlistButton = false;
                p.AvailableForPreOrder = false;
                p.CallForPrice = false;
                p.OldPrice = 0;
                p.ProductCost = 0;
                p.CustomerEntersPrice = false;
                p.MinimumCustomerEnteredPrice = 0;
                p.MaximumCustomerEnteredPrice = 0;
                p.HasTierPrices = false;
                p.HasDiscountsApplied = false;
                p.Weight = 0;
                p.Length = 0;
                p.Width = 0;
                p.Height = 0;
                p.DisplayOrder = 0;
                p.Deleted = false;
                p.CreatedOnUtc = DateTime.Now;
                p.UpdatedOnUtc = DateTime.Now;




                db.Products.Add(p);
                db.SaveChanges();
                return p;
            }
            else
            {
                return null;
            }

        }
        public byte[] ImageToByteArrayFromFilePath(string imagefilePath)
        {
            byte[] imageArray = File.ReadAllBytes(imagefilePath);
            return imageArray;
        }
        public Picture SaveToPicture(byte[] binary,string mimetype, string seo,bool isnew)
        {
            Picture p = new Picture();
            p.PictureBinary = binary;
            p.MimeType = mimetype;
            p.SeoFilename = seo;
            p.IsNew = isnew;
            db.Pictures.Add(p);
            db.SaveChanges();
            return p;
        }
        public void SaveToProduct_Pic(int proId, int picId,int disPlay)
        {
            Product_Picture_Mapping ppm = new Product_Picture_Mapping();
            ppm.ProductId = proId;
            ppm.PictureId = picId;
            ppm.DisplayOrder = disPlay;
            db.Product_Picture_Mapping.Add(ppm);
            db.SaveChanges();
        }
        public void SaveToUrlRecord(int entityId, string enityName, string slug, bool isAc, int lanId)
        {
            UrlRecord u = new UrlRecord();
            u.EntityId = entityId;
            u.EntityName = enityName;
            u.Slug = slug;
            u.IsActive = isAc;
            u.LanguageId = lanId;
            db.UrlRecords.Add(u);
            db.SaveChanges();
        }
        public void SaveToProduct_Category(int proId, int cateId, bool isFeatured, int display)
        {
            Product_Category_Mapping p = new Product_Category_Mapping();
            p.ProductId = proId;
            p.CategoryId = cateId;
            p.IsFeaturedProduct = isFeatured;
            p.DisplayOrder = display;
            db.Product_Category_Mapping.Add(p);
            db.SaveChanges();
        }
        public void SaveToProduct_Manu(int proId, int manuId, bool isFeatured, int display)
        {
            Product_Manufacturer_Mapping p = new Product_Manufacturer_Mapping();
            p.ProductId = proId;
            p.ManufacturerId = manuId;
            p.IsFeaturedProduct = isFeatured;
            p.DisplayOrder = display;
            db.Product_Manufacturer_Mapping.Add(p);
            db.SaveChanges();
        }
        public News SaveToNews(News n)
        {
            db.News.Add(n);
            db.SaveChanges();
            return n;
        }
        public Boolean UrlVitedInToday(string url)
        {
            var list = db.News.Where(m=>m.CreatedOnUtc>= DateTime.Today).ToList();
            if(list.Count()>0)
            for (int i = 0; i < list.Count(); i++)
            {
                if(list[i].Url != null )
                if (list[i].Url.Equals(url) )
                {
                    return true;
                    break;
                }

            }
            return false;
        }
        //code download image copy 
        public List<string> PhotoDownloader(List<string> aList, string outputDir, string codePro)
            {
             Image imageStream = null;
                DateTime dt = DateTime.Now;
             //   String newDir = String.Format("{0:yyyy_mm_dd}", dt);
              string folder= outputDir+"/"+codePro;
              List<string> listDir = new List<string>();
              if (!Directory.Exists(folder) && aList != null)
              {
                  Directory.CreateDirectory(outputDir + "/" + codePro);
                  int ctr = 1;
                  for (int i = 0; i < aList.Count(); i++)
                  {
                      try
                      {
                          System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(aList[i]);
                          httpWebRequest.AllowWriteStreamBuffering = true;
                          httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
                          httpWebRequest.Timeout = 30000; //30 seconds
                          System.Net.WebResponse webResponse = httpWebRequest.GetResponse();
                          System.IO.Stream webStream = webResponse.GetResponseStream();
                          imageStream = Image.FromStream(webStream);
                          webResponse.Close();
                          webResponse.Close();
                      }
                      catch (Exception e)
                      {
                          Console.WriteLine("Error: " + e.Message);
                      }
                      Console.WriteLine((ctr++) + "Saving..." + aList[i]);

                      //String newFile = aList[i].Substring(aList[i].LastIndexOf("/") + 1);

                      String filename = i + ".jpg";

                      string urlPc= outputDir + "/" + codePro + "/" + filename;
                      imageStream.Save(urlPc);
                      listDir.Add(urlPc);
                  }
                  return listDir;

              }
              else
              {
                  return null;
              }
              
              
            }
        
    }
  
   
    //public Image DownloadImageFromUrl(string imageUrl)
    //    {
    //        System.Drawing.Image image = null;

    //        try
    //        {
    //            System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
    //            webRequest.AllowWriteStreamBuffering = true;
    //            webRequest.Timeout = 30000;

    //            System.Net.WebResponse webResponse = webRequest.GetResponse();

    //            System.IO.Stream stream = webResponse.GetResponseStream();

    //            image = System.Drawing.Image.FromStream(stream);

    //            webResponse.Close();
    //        }
    //        catch (Exception ex)
    //        {
    //            return null;
    //        }

    //        return image;
    //    }

}
